import { FindOptions, MongoClient, ObjectId, UpdateFilter } from "mongodb";

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url);

async function run() {
  try {
    await client.connect();
    const db = client.db("hello");
    const res = await db.command({ ping: 1 }); // 测试数据库是否成功
    console.log("connected", res);
    // 数据的插入
    const userCollection = db.collection("user");
    // replace: 完全替换
    // const replaceDoc = await userCollection.replaceOne({ name: "AD" }, { name: "ls", age: 40 });
    // console.log(replaceDoc);

    // update: 局部替换
    // $set 新增，修改
    const updateFilter: UpdateFilter<{ name: string; age: number }> = {
      $set: {
        name: "Lebron",
      },
      $inc: {
        age: 1,
      },
    };
    const updateDoc = await userCollection.updateOne({ _id: new ObjectId("68ce7120858262e08cfed019") }, updateFilter);
    console.log(updateDoc);
  } catch (error) {
    console.error("error", error);
  } finally {
    await client.close();
  }
}

run();
